package com.examples

import android.os.SystemClock
import android.view.View
import android.view.ViewGroup
import androidx.annotation.IdRes
import com.example.zjx8969.myapplication.R
import java.lang.ref.WeakReference

/**
 * @param listener 业务listener
 * @param intervalTime 两次点击事件的点击时间, 单位是【毫秒】
 * @param rootViewId activity/Fragment/View rootView的id，在它的层级之下的view共享一个点击时间的间隔
 */
class TimeoutClickListener @JvmOverloads constructor(val listener: View.OnClickListener, val intervalTime: Int = 2000, @IdRes val rootViewId: Int = R.id.rootViewId) : View.OnClickListener {
    private var topViewReference: WeakReference<View>? = null

    override fun onClick(v: View?) {
        v?.let { view ->
            val topView = getTopView(view)
            if (topView == null) {
                throw IllegalArgumentException("don't find rootView who's id is $rootViewId")
            } else {
                val lastClickTime = topView.getTag(rootViewId)?.toString()?.toLong() ?: -1
                if (SystemClock.uptimeMillis() - lastClickTime >= intervalTime) listener.onClick(v)
                topView.setTag(rootViewId, SystemClock.uptimeMillis())
            }


        }
    }

    private fun getTopView(it: View): View? {
        var topView = topViewReference?.get()
        if (topView == null) {
            var parentView = it.parent
            while (parentView != null) {
                if (parentView is ViewGroup && parentView.id == rootViewId) {
                    topView = parentView
                    topViewReference = WeakReference(topView)
                    break
                }
                parentView = parentView.parent
            }
        }
        return topView
    }

}